from django.http import JsonResponse
from tools.jwt_token import SimpleJWT
import re

class JWTAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.jwt = SimpleJWT()
        # 定义不需要认证的路径白名单
        self.exempt_paths = [
            re.compile(r'^/login/'),
            re.compile(r'^/image/'),
            re.compile(r'^/code/'),
        ]

    def __call__(self, request):
        # 检查请求路径是否在白名单中
        if any(pattern.match(request.path) for pattern in self.exempt_paths):
            return self.get_response(request)

        # 从请求头获取token
        auth_header = request.headers.get('Authorization', '')
        if not auth_header.startswith('Bearer '):
            return JsonResponse(
                {'code': 401, 'msg': '未提供认证令牌'},
                status=401
            )

        token = auth_header.split(' ')[1]
        payload = self.jwt.verify_token(token)

        if not payload:
            return JsonResponse(
                {'code': 401, 'msg': '无效或过期的令牌'},
                status=401
            )

        # 将用户信息添加到request对象中
        request.user_id = payload.get('user_id')
        return self.get_response(request)